﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Mathematics;

public class AutoLeading : MonoBehaviour
{

    public Transform[] leadingPoints;
    public float movingSpeed;
    private int index = 0;
    private bool forward = false;
    public bool IsThisSpriteFacingRight;
    private void OnDrawGizmos()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawLine(transform.position, leadingPoints[0].position);
        for (int i = 0; i < leadingPoints.Length - 1; i++)
        {
            Gizmos.DrawLine(leadingPoints[i].position, leadingPoints[i + 1].position);
        }
    }
    private void Start()
    {
        if ((transform.position - leadingPoints[0].position).x > 0)
        {
            transform.localScale = new Vector3(Mathf.Abs(transform.localScale.x) * (IsThisSpriteFacingRight ? -1 : 1), 1, 1);
        }
        else transform.localScale = new Vector3(Mathf.Abs(transform.localScale.x) * (IsThisSpriteFacingRight ? 1 : -1), 1, 1);
        movingSpeed /= 100;
    }
    // Update is called once per frame
    void Update()//在update函数中判断，fixedupdate中调用。
    {
        if (transform.position == leadingPoints[index].position)//to avoid always ongoing.
        {
            if (index < leadingPoints.Length - 1)
            {
                index++;
                if ((leadingPoints[index].position - leadingPoints[index - 1].position).x < 0)
                {
                    transform.localScale = new Vector3(Mathf.Abs(transform.localScale.x) * (IsThisSpriteFacingRight ? -1 : 1), 1, 1);
                }
                else transform.localScale = new Vector3(Mathf.Abs(transform.localScale.x) * (IsThisSpriteFacingRight ? 1 : -1), 1, 1);
                forward = true;
            }
        }
        else
        {
            forward = false;
        }
    }

    private void FixedUpdate()
    {
        if (!forward)
        {
            transform.position = Vector2.MoveTowards(transform.position, leadingPoints[index].position, movingSpeed);
        }
    }
}
